<?php
/**
 * #辅助函数，全局通用
 * Created by PhpStorm.
 * User: cdsile
 * Date: 2018/12/17
 * Time: 16:22
 */

include LIB_PATH.'/Log/Log.php'; # 日志；
include LIB_PATH.'/Ioc/Ioc.php'; # 依赖注入ioc 容器；
/**
 * 获取admin 模块 config配置项
 */
if (!function_exists('config')) {
    function config($val='account',$M=null){
//        $common = new Common();
//        $M = $M?: PLATFORM;
//        $common->autoload_conf(APP_PATH.$M.DS. "config");
        $configs = [];
        if (isset($GLOBALS['config_'.$val])) {
            $configs = $GLOBALS['config_'.$val];
        }
        $arr = explode('.', $val);
        # 多级数组获取
        if ( count($arr)>1) {
            $data = $configs = $GLOBALS['config_'.$arr[0]];
            unset($arr[0]);
            foreach ($arr as  $key=>$value ) {
                if (!isset($data[$value])) {
                    return null;
                }
//                var_dump($value);die;
                $data = $data[$value];
            }
            return $data;
        }

        return  $configs;
    }
}

/**
 * 成功数据返回
 */
if(!function_exists("returnSuccess")) {

    function returnSuccess($data, $msg='success',$code=0) {
        header('Access-Control-Allow-Origin:*');
        header('content-type:application/json;charset=utf-8');
        $arr = [
            'data' => $data,
            'msg' => $msg,
            'code' => $code,//200
        ];
        exit(json_encode($arr));
    }

}

/**
 * 失败数据返回
 */
if(!function_exists("returnFail")) {

    function returnFail($data, $msg='fail',$code=1) {
        header('content-type:application/json;charset=utf-8');
        $arr = [
            'data' => $data,
            'msg' => $msg,
            'code' => $code,
        ];
        exit(json_encode($arr));
    }

}
/**
 * table 组件需要返回的数据
 * @param $data
 * @param string $msg
 * @param $code
 */
if(!function_exists("returnTableData"))  {
 function returnTableData($data, $count,$page, $msg ='' , $code=0){
        $arr = [
            'count'=> $count,
            'data' => $data,
            'page' => $page,
            'code' => $code,
            'msg'  => $msg
        ];
     exit(json_encode($arr));
    }
}
/**
 * 写入log
 * @param $log
 */
if(!function_exists('setLog')){
    function setLog($param,$filename='log.log') {
        $class = Request::channel('wechat')->set($param,$filename);
        return $class;
    }

}
/**
 * 设置通道地址
 * @param $stack
 */
if(!function_exists('LogChannel')) {
    function LogChannel($stack)
    {
        $class =   Log::channel($stack);
        return $class;
    }
}
if(!function_exists("cache")) {
    function cache(...$param) {
        $cache = new \Symfony\Component\Cache\Simple\FilesystemCache();

        # 第一个元素是数组，
        if(is_array($param[0])) {
            $cache->setMultiple($param[0]);
            return $cache;
        }
        # 元素数量为2 且第一个不是数组
        if(count($param)>=2&&!is_array($param[0])) {
            $cache->set($param[0],$param[1]);
            return $cache;
        }

        # 取元素
        if (count($param)==1) {
            $caceValue = $cache->get($param[0]);
            return $caceValue;
        }
        return $cache;
    }
}
if(!function_exists("app")) {
    function app($class,$pre='front',$dir='') {
        $arr = explode('_',$class);
        $modelname = implode('/',$arr);
        $dir = $dir?DS.$dir:'';
        $file = APP_PATH.$pre.DS. "models" .$dir.DS.$modelname.'.class.php';

        if(file_exists($file))
        {
            include_once $file;
            $app = Ioc::getInstance($class);

           return $app;
        } else {
            exit($file.' not exists ');
        }

    }
}

/**
 * Ajax 返回
 */
if(!function_exists("returnResponse")) {

    function returnResponse($data) {
        header('content-type:application/json;charset=utf-8');
        exit(json_encode($data));
    }

}

/**
 *  根据2个相同的数据   合并2个数组 1对1的数组
 */
if(!function_exists("mergeOnetMore")) {

    function mergeOnetoMore(array $arr,array $data,$param) {
        $akey = '';
        $dkey = '';

        if(is_array($param)) {
            $akey = $param[0];
            $dkey = $param[1];
        }
        foreach ($arr as $key=> &$value) {
            $value['dev'] = [];
            foreach ($data as $k=>$v) {
                if($value[$akey] == $v[$dkey]) {
                    array_push($value['dev'],$v);
                }
            }
        }
    return $arr;
    }

}


if(!function_exists("mergeOnetoOne")) {

    function mergeOnetoOne(array $arr,array $data,$param) {
        $akey = '';
        $dkey = '';

        if(is_array($param)) {
            $akey = $param[0];
            $dkey = $param[1];
        }
        foreach ($arr as $key=> &$value) {
            foreach ($data as $k=>$v) {
                if($value[$akey] == $v[$dkey]) {
                    $value['dev'] = $v;

                }
            }
        }
        return $arr;
    }

}

# 获取uid
if(!function_exists('getSessionUid')) {
    function getSessionUid(){
        $user_id =  $_SESSION['userinfo']['id'];
        # 测试
        $user_id = 1;
        return $user_id;
//        return 1;
    }
}

# 批量加密
if(!function_exists('encrypt')) {
    function encrypt($data,$paramName,$commonEle){
        foreach ($data as  $key=>$val){
            if (is_array($val)) {
                $data[$key] = encrypt($val,$paramName,$commonEle);
            }else {
                if ($key == $paramName||($key&&is_array($paramName)&&in_array($key, $paramName))) {
                    $data[$key] = $commonEle->encrypt($val);
                }
            }
        }
        return $data;
    }
}

function pr($arr) {
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
}


/**
 * Notice: 生成文件夹
 * Date: 2019/2/27
 * Time: 10:26
 * @author dongdong
 * @param $filename
 * @param $writetext
 * @return int
 */
function jwritefile($filename, $writetext='') {
    $position = strrpos($filename,'/');
    $path = substr($filename,0,$position);
    if(!file_exists($path)){
        mkdir($path,0777,true);
    }
    $updatetime = filemtime($filename);
    $difftime = time()-$updatetime;
    if($difftime > 3600){//时间大于一个小时
        if (@file_put_contents($filename, $writetext, LOCK_EX)) {
            return 1;
        }else {
            return -1;
        }
    }else{
        return 0;//时间小于1一个钟头，不用生成
    }
}

# 错误处理
if(!function_exists('customError')) {
    function customErrorr($error_level,$error_message,$error_file,$error_line,$error_context){
         switch ($error_level) {
             case E_WARNING:
                 return true;
//                 die('E_WARNING');
                 break;
             case E_NOTICE:
                 return true;
//                 die('E_NOTICE');
                 break;
             case E_ERROR:
                 break;
             case E_USER_ERROR:
                 break;
             case E_USER_WARNING:
                 return true;
//                 die('E_USER_WARNING');
                 break;
             case E_USER_NOTICE:
                 return true;
//                 die('E_USER_NOTICE');
                 break;
         }
        /*if($error_level !=E_USER_ERROR|| $error_level != E_ERROR) {
            return false;
        }*/

        $string = file_get_contents(ROOT.'storage/errorpage/500.html');
        $error_str = '<br><br>'.$error_file.'<br>line:'.$error_line;
        if (config('system.debug') ) {
            $dir = getcwd();
            $span = "<div style='font-size: 1rem;color: #ffa100;'>".$error_message.$error_str."</div>";
            $content = main($dir, $span);
            $span = str_replace($content,'', $span);
            $string =  str_replace('{{}}',$span,$string);
        }  else {
            $string =  str_replace('{{}}','The requested URL caused an internal server error.',$string);
        }
        LogChannel('log')->error($error_message.$error_str);
        die($string);
    }
}

/**
 * Notice: 匹配2个字符 中 相同的部分
 * Date: 2019/3/28
 * Time: 21:22
 * @author dongdong
 * @param string $str1
 * @param string $str2
 * @return bool|string
 */
function longest($str1 ='' , $str2 =''){
    $start=0; $end=2; $longest = ''; $len = strlen( $str1 );

    // 找到两个字符串完全相同的部分，赋值给 $longest ，当找到有最长的字符串，就替换 $longest
    for ($i=0; $i < $len; ) {
        $part = substr($str1, $start, $end);
        if(strpos( $str2, $part) == true){
            if( strlen($part) > strlen($longest)){
                $longest = $part;
            }
            $end++;
        }else{
            $i++;
            $start = $i - 1;
            $end = 2;
        }
    }
    return $longest;
}

/**
 * 找两个字符串相同的部分
 **/
function main($str1, $str2)
{
    //将字符串转成数组
    $arr1 = str_split($str1);
    $arr2 = str_split($str2);
    //计算字符串的长度
    $len1 = strlen($str1);
    $len2 = strlen($str2);
    //初始化相同字符串的长度
    $len = 0;
    //初始化相同字符串的起始位置
    $pos = -1;
    for ($i = 0; $i < $len1; $i++) {
        for ($j = 0; $j < $len2; $j++) {
            //找到首个相同的字符
            if ($arr1[$i] == $arr2[$j]) {
                //判断后面的字符是否相同
                for ($p = 0; (($i + $p) < $len1) &&
                (($j + $p) < $len2) &&
                ($arr1[$i + $p] == $arr2[$j + $p]) &&
                ($arr1[$i + $p] <> ''); $p++) ;
                if ($p > $len) {
                    $pos = $i;
                    $len = $p;
                }
            }
        }
    }
    if ($pos == -1) {
        return;
    } else {
        return substr($str1, $pos, $len);
    }
}

/**
 * Notice: 静态资源路径
 * Date: 2019/3/28
 * Time: 20:46
 * @author dongdong
 */
function resourceurl() {
    return  $resource = '/resources';
}

/**
 * Notice: 验证码生成
 * Date: 2019/3/28
 * Time: 16:16
 * @author dongdong
 */
 function captchacode()
{
//        ob_clean();
    // 1 创建画布
    $img = imagecreatetruecolor(100, 30);
    // 2 画一个矩形并填充
    $bgcolor = imagecolorallocate($img, mt_rand(120,255), mt_rand(120,255), mt_rand(120,255));
    imagefilledrectangle($img, 0, 0, 100, 30, $bgcolor);
    // 3 在画布上进行操作
    // 3.1 定义字符串
    $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
    // 3.2 定义变量，存放验证码
    $code = '';
    // 3.2 加载自定义字体
    $font_file = ROOT."storage/front/elephant.ttf";   //'./comic.ttf';
    if (!file_exists($font_file) ) {
        user_error($font_file."  front  NOT FOUND \n\r ",E_USER_ERROR);
     }
    // 3.3 生成文字部分
    for ($i = 0; $i < 4; $i++) {
        // 定义字体颜色
        $fontcolor = imagecolorallocate($img, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));
        // 文字内容
        $content = substr($str, mt_rand(0, strlen($str)-1), 1);
        // 设置显示坐标
        $x = ($i * 100 / 4) + mt_rand(5, 10);
        $y = mt_rand(17, 22);
        // 把文字填充到画布
        imagefttext($img, 15, mt_rand(-5, 5), $x, $y, $fontcolor, $font_file, $content);
        // 将文字内容赋值给 code 变量
        $code .= $content;
    }
    // 3.4 将大写字母转换为小写
    $code = strtolower($code);
    // 3.5 给 session 赋值
    $_SESSION['captcha']  = $code;
    // 3.6 设置干扰元素
    for ($i = 0; $i < 200; $i++) {
        $pointcolor = imagecolorallocate($img, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
        imagesetpixel($img, mt_rand(1, 99), mt_rand(1, 29), $pointcolor);
    }
    // 3.7 设置干扰线
    for ($i = 0; $i < 3; $i++) {
        $linecolor = imagecolorallocate($img, mt_rand(50, 200), mt_rand(50, 200), mt_rand(50, 200));
        imageline($img, mt_rand(1, 99), mt_rand(1, 29), mt_rand(1, 99), mt_rand(1, 29), $pointcolor);
    }
    // 4 向浏览器输出图片头信息
    header('Content-Type:image/png');
    // 5 输出图片到浏览器
    imagepng($img);
    // 6 销毁图片
    imagedestroy($img);
    return $code;
}

//文件格式验证
 function file_format($str){
    // 取文件后缀名
    $str=strtolower(pathinfo($str, PATHINFO_EXTENSION));
    // 图片格式
    $image=array('webp','jpg','png','ico','bmp','gif','tif','pcx','tga','bmp','pxc','tiff','jpeg','exif','fpx','svg','psd','cdr','pcd','dxf','ufo','eps','ai','hdri');
    // 视频格式
    $video=array('mp4','avi','3gp','rmvb','gif','wmv','mkv','mpg','vob','mov','flv','swf','mp3','ape','wma','aac','mmf','amr','m4a','m4r','ogg','wav','wavpack');
    // 压缩格式
    $zip=array('rar','zip','tar','cab','uue','jar','iso','z','7-zip','ace','lzh','arj','gzip','bz2','tz');
    // 文档格式
    $text=array('exe','doc','ppt','xls','wps','txt','lrc','wfs','torrent','pdf','pps','host','box','docx','word','perfect','dot','dsf','efe','ini','json','lnk','log','msi','ost','pcs','tmp','xlsb');
    $pdf = array('pdf','pps','word','docx','ppt','doc','wps','xls','xlsx');
    // 'html','htm','java','js','css','less','php',
    // 匹配不同的结果
    switch ($str) {
        case in_array($str, $image):
            return 'image';
            break;
        case in_array($str, $video):
            return 'video';
            break;
        case in_array($str, $zip):
            return 'zip';
            break;
        case in_array($str, $text):
            return 'text';
            break;
        case in_array($str, $pdf):
            return 'pdfwordxlsx';
            break;
        default:
            return 'null';
            break;
    }
}




